<template>
  <div class="approval-container">
    <!-- 搜索条件区域 -->
    <div class="search-wrapper">
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form" label-width="85px"
        style="text-align: left">
        <div>
          <el-row>
            <el-col :span="6">
              <el-form-item label="订单编号" prop="orderCode">
                <el-input v-model="searchForm.orderCode" placeholder="订单编号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center;">
              <el-form-item label="员工账号" prop="userName">
                <el-input v-model="searchForm.userName" placeholder="员工账号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center;">
              <el-form-item label="员工昵称" prop="nickName">
                <!-- <el-input v-model="searchForm.supplierName" placeholder="食材清单" clearable></el-input> -->
                <el-input v-model="searchForm.nickName" placeholder="员工昵称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: right;">
              <el-form-item label="用餐时间" prop="date">
                <!-- <el-input v-model="searchForm.date" placeholder="用餐时间" clearable></el-input> -->
                <el-date-picker v-model="searchForm.date" type="date" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div style="margin-top: 10px;">
          <el-row>
            <el-col :span="6">
              <el-form-item label="就餐地点" prop="siteName">
                <!-- <el-input v-model="searchForm.siteName" placeholder="就餐地点" clearable></el-input> -->
                <el-select v-model="searchForm.siteName" clearable placeholder="请选择" style="width: 100%;">
                  <el-option v-for="(item, index) in zhand" :key="index" :label="item.siteName" :value="item.siteName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center;">
              <el-form-item label="创建日期" prop="date">
                <el-date-picker v-model="searchForm.createTime" type="date" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="text-align: right;">
              <div class="search-actions">
                <el-button style="background-color: #4C6EE2;color: white;" size="small"
                  @click="handleSearch">搜索</el-button>
                <el-button size="small" @click="resetSearch">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>

    <!-- 审批状态筛选 -->
    <div class="status-filter" style="display: flex;justify-content: space-between;">
      <el-radio-group v-model="radio" style="margin-top: 9px;margin-left: 17px;" @input="inputGroup">
        <el-radio :label="1">全部</el-radio>
        <el-radio :label="2">已下单</el-radio>
        <el-radio :label="3">未取餐</el-radio>
      </el-radio-group>
      <div>
        <el-button type="success" size="small" plain icon="el-icon-edit" @click="handleBatchEdit"
          v-hasPermi="['food:dish:edit']">修改</el-button>
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出</el-button>
        <el-button type="danger" size="small" plain icon="el-icon-delete-solid" @click="handleBatchDelete"
          v-hasPermi="['food:dish:remove']">删除</el-button>
      </div>
    </div>

    <!-- 审批数据表格 -->
    <div class="table-wrapper">
      <el-table :data="tableData" style="width: 100%" v-loading="loading" :header-cell-style="{ background: '#f8f8f9' }"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column prop="orderCode" label="订单编号"></el-table-column>
        <el-table-column prop="userName" label="员工账号" align="left"></el-table-column>
        <!-- <el-table-column prop="nickName" label="员工昵称" align="left">
        </el-table-column> -->
        <el-table-column prop="date" label="用餐时间" align="left">
          <template slot-scope="scope">
            {{ scope.row.date }}
            （{{getDayOfWeek(scope.row.date)}}）
          </template>
          <!-- getDayOfWeek -->
        </el-table-column>
        <el-table-column prop="content" label="订单内容" width="200" align="left">
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" align="right">
        </el-table-column>
        <el-table-column prop="actualAmount" label="实付金额" align="right">
        </el-table-column>
        <el-table-column prop="type" label="取餐方式" align="left">
          <template slot-scope="scope">
            {{ scope.row.type == 0 ? "堂食" : "配送" }}
          </template>
        </el-table-column>
        <el-table-column prop="siteName" label="就餐地点" align="left">
        </el-table-column>
        <el-table-column prop="phone" label="联系方式" align="left">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="left">
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)" :style="{ backgroundColor: scope.row.status == 2 && 'rgb(237, 240, 252)',color: scope.row.status == 2 && '#4C6EE2'}">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)" style="color: #4C6EE2;"
              v-hasPermi="['food:dish:edit']" v-if="scope.row.status == 0 || scope.row.status == 1">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" style="color: #4C6EE2;"
              v-hasPermi="['food:dish:remove']">删除</el-button>
            <!-- <el-button type="text" size="small" @click="handleDelete(scope.row)" style="color: #4C6EE2;" v-hasPermi="['food:dish:remove']">取餐</el-button> -->
            <el-button type="text" size="small" @click="picked(scope.row,1)" v-if="scope.row.status == 1" style="color: #4C6EE2;"
              v-hasPermi="['food:dish:remove']">未取餐</el-button>

              <el-button type="text" size="small" @click="picked(scope.row,2)" v-if="scope.row.status == 5" style="color: #4C6EE2;"
              v-hasPermi="['food:dish:remove']">撤回未取餐</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <!-- <el-pagination 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange"
            :current-page="pagination.pageNum" 
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize" 
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          ></el-pagination> -->
        <pagination v-show="pagination.total > 0" :total="pagination.total" :page.sync="pagination.pageNum"
          :limit.sync="pagination.pageSize" @pagination="fetchData" />

      </div>
    </div>

    <!-- 新增/编辑弹框 -->
    <el-dialog :title="dialogTitle" v-if="dialogVisible" :visible.sync="dialogVisible" width="60%" style="border-radius: 10px;"
      @close="resetForm">
      <template #title>
        <div class="custom-dialog-title">
          <div
            style="display: flex;border-bottom: 1px solid rgba(0, 0, 0, 0.05);padding-bottom: 20px;padding-left: 30px;">
            <div
              style="background-color: #4C6EE2;border-radius: 20px;width: 4px;margin-right: 8px;height: 20px;margin-top: 6.5px;">
            </div>
            <span class="title-text" style="font-family: Source Han Sans;
          font-size: 20px;
          font-weight: 500;
          line-height: 31px;
          text-align: center;
          letter-spacing: normal;
          color: #3D3D3D;">{{ dialogTitle }}</span>
          </div>
        </div>
      </template>
      <div style="
        font-family: Source Han Sans;
        font-size: 20px;
        font-weight: 500;
        line-height: 31px;
        margin-left: 30px;
        display: flex;
        letter-spacing: normal;
        color: #3D3D3D;">
        <!-- <svg-icon style="margin-right: 10px;" icon-class="@/assets/images/updatesvn.svg" class="item-icon" /> -->
        <img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 5px;">
        基本信息
      </div>
      <el-form ref="foodForm" :model="form" :rules="rules" label-width="120px" class="dialogN" label-position="top"
        style="padding: 30px;padding-top: 10px;" size="medium">

        <el-row :gutter="30">
          <el-col :span="8">
            <el-form-item label="用餐日期" prop="date">
              <el-date-picker v-model="form.date" type="date" style="width: 100%;"
                value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="form.phone" placeholder="联系方式" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单金额" prop="totalAmount">
              <el-input v-model="form.totalAmount" :min="0" placeholder="订单金额" 实付金额 style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="30">

          <el-col :span="8">
            <el-form-item label="实付金额" prop="actualAmount">
              <el-input v-model="form.actualAmount" :min="0" placeholder="实付金额" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="取餐方式" prop="type">
              <!-- {{ form.type }} -->
              <el-select v-model="form.type" @change="handerchange" placeholder="请选择" style="width: 100%;">
                <el-option v-for="(item, index) in pickupList" :key="index" :label="item.label"
                  :value="String(item.value)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="就餐地点" prop="siteId" v-if="form.type == 1">
              <el-select v-model="form.siteId" placeholder="请选择" style="width: 100%;">
                <el-option v-for="(item, index) in zhand" :key="index" :label="item.siteName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="font-size: 20px;font-weight: 600;padding: 12px 0;display: flex;">
          <img src="@/assets/images/updatesvn.svg" alt="" style="margin-top: -6px;padding-right: 5px;">

          用餐信息
          <!-- <el-button plain style="background-color: rgb(237, 240, 252);color: #4C6EE2;border: 1px solid #4C6EE2;margin-left: 7px;margin-top: -3px;" @click="addIngredients">添加套餐</el-button> -->
        </div>

        <el-row :gutter="30">
          <el-col :span="20" style="padding-bottom: 0px;">
            <!-- <el-form-item label="类型：" prop="totalAmount" class="inline-form-item"> -->
              <!-- {{ dict.type.food_eat_type }} -->
                <!-- {{ radioType }} -->
              <span style="font-weight: 600;">类型：</span><el-radio-group v-model="radioType" style="margin-top: 4px;margin-left: 17px;" @input="qiehuan">
                <el-radio  v-for="(item, index) in dict.type.food_eat_type" :key="item.value"
                  :label="item.value - 1">{{ item.label }}</el-radio>

              </el-radio-group>
              <!-- <el-radio v-model="radioType" label="2">备选项</el-radio> -->
            <!-- </el-form-item> -->
          </el-col>

        </el-row>

        <div v-if="haveDinner">
          <el-row :gutter="30" v-for="(item, index) in breakfastList[0]" :key="index">
            <el-col :span="8">
              <el-form-item label="套餐">
                <el-select v-model="item.comboId" placeholder="请选择" style="width: 100%;" filterable clearable>
                  <el-option v-for="(items, indexs) in ingredientList.filter(el => el.type == (radioType + 1))"
                    :key="indexs" :label="items.comboName" :value="items.comboId"
                    :disabled="isIngredientDisabled(items.comboId, indexs)"
                    >
                    <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                      <span>{{ items.comboName }}</span>
                      <div>
                        <span v-for="(value,index) in items.listItem " :key="index">
                          {{ value.foodDish.foodName }}
                        </span>
                      </div>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="数量">
                <el-input v-model="item.num" style="width: 80%;" placeholder="数量" clearable></el-input>
                <i class="el-icon-circle-plus-outline" v-if="index == 0" @click="addCombo(index)"
                  style="margin-left: 5px; cursor: pointer;font-size: 20px;"></i>
                <i class="el-icon-delete" v-if="index !== 0" @click="deleteFoodItems(1,index,1)"
                  style="margin-left: 5px; cursor: pointer;font-size: 20px;"></i>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30" v-for="(itemye, index) in breakfastList[1]" :key="index">
            <el-col :span="8">
              <el-form-item label="菜品">
                <el-select v-model="itemye.foodId" placeholder="请选择" style="width: 100%;" filterable clearable>
                  <el-option v-for="(items, indexyh) in cuisineList.filter(el => el.type == (radioType + 1))" :key="indexyh"
                    :label="items.foodName" :value="items.foodId"
                    :disabled="isIngredientDisableds(items.foodId, indexyh)"
                    >
                    <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                      <span>{{ items.foodName }}</span>
                      <span style="color: #67C23A; font-weight: 500;">￥{{ items.price }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="数量">
                <el-input v-model="itemye.num" style="width: 80%;" placeholder="数量" clearable></el-input>
                <i class="el-icon-circle-plus-outline" v-if="index == 0" @click="addFood(index)"
                  style="margin-left: 5px; cursor: pointer;font-size: 20px;"></i>
                <i class="el-icon-delete" v-if="index !== 0" @click="deleteFoodItems(1,index,2)"
                  style="margin-left: 5px; cursor: pointer;font-size: 20px;"></i>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: center;">

        <el-button @click="dialogVisible = false"
          style="background-color: white;color: #4C6EE2;border: 1px solid #4C6EE2;">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" style="background-color: #4C6EE2;color: white;"
          :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
        :title="dialogTitle"
        :visible.sync="deriveVisible"
        width="600px"
        style="border-radius: 10px;"
        @close="deriveVisible = flase"
      >
      <template #title>
      <div class="custom-dialog-title">
        <div style="display: flex;border-bottom: 1px solid rgba(0, 0, 0, 0.05);padding-bottom: 20px;padding-left: 30px;">
          <div style="background-color: #4C6EE2;border-radius: 20px;width: 4px;margin-right: 8px;height: 20px;margin-top: 6.5px;">
          </div>
          <span class="title-text" style="font-family: Source Han Sans;
          font-size: 20px;
          font-weight: 500;
          line-height: 31px;
          text-align: center;
          letter-spacing: normal;
          color: #3D3D3D;">导出订单</span>
        </div>
      </div>
    </template>

    <div style="display: flex;justify-content: space-between">
      <div>
        <img src="@/assets/images/purchasing.png" style="width: 539px;height: 242px;" alt="">
        <div style="text-align: center;">
          <el-radio v-model="fsds" label="1">订餐表（午餐总表）</el-radio>
        </div>
      </div>
      <!-- <div>
        <img src="@/assets/images/reservation.png" style="width: 539px;height: 224px;" alt="">
        <div style="text-align: center;margin-top: 20px;">
          <el-radio v-model="deriveRadio" label="2">待采购清单</el-radio>
        </div>
      </div> -->
    </div>

    <div style="margin-top: 20px;display: flex;">
      <div>
        <span style="color: black;font-size: 16px;">导出时间：</span>
            <el-date-picker
            v-model="exportTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            format="yyyy 年 MM 月 dd 日"
            size="mini" 

            value-format="yyyy-MM-dd"
            end-placeholder="结束日期">
          </el-date-picker>
      </div>
    
    </div>
    <div style="margin-left: 30px;margin-top: 20px;">
        <span style="color: black;font-size: 16px;">类型：</span>
        <el-radio-group v-model="eatType">

                <el-radio 
                  :label="1">早餐</el-radio>
                  <el-radio 
                  :label="2">午餐</el-radio>
                  <el-radio 
                  :label="3">晚餐</el-radio>
                </el-radio-group>

      </div>

      <div style="margin-left: 30px;margin-top: 20px;">
        <span style="color: black;font-size: 16px;">季节：</span>
        <el-radio-group v-model="deriveRadio">
                <el-radio 
                  label="1">淡季</el-radio>
                  <el-radio 
                  label="2">旺季</el-radio>
                </el-radio-group>

      </div>


      <div style="margin-top: 20px;">
        <span style="color: black;font-size: 16px;">订单类型：</span>
        <el-radio-group v-model="bowType">
                <el-radio 
                  :label="1">订单</el-radio>
                  <el-radio 
                  :label="2">轻食订单</el-radio>
                </el-radio-group>

      </div>
   

        <div slot="footer" class="dialog-footer" style="text-align: center;">

          <el-button @click="deriveVisible = false" style="background-color: white;color: #4C6EE2;border: 1px solid #4C6EE2;">取 消</el-button>
          <el-button type="primary" @click="exportConfirmed" style="background-color: #4C6EE2;color: white;" :loading="submitting">确 定</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { getList, dishAdd, dishUpdate, deleteInent,CombnoTakeMealte, uploading, fooorderulars, ComboUpdate,fooexcelrs,sttofnoTakeMeal } from '@/api/indent'
import { getList as getlists } from '@/api/combo'
import { getToken } from "@/utils/auth"
import { getList as GETcuisineList } from '@/api/cuisine'
import nameding from "@/plugins/download.js"

import { listDept, getDept } from "@/api/system/station"
export default {
  name: "DishManagement",
  dicts: ['foot_ingredient_type', "food_eat_type"],
  data() {
    const [monday, sunday] = this.getCurrentWeekRange();

    return {
      eatType:2,
      deriveRadio: "1",
      fsds:"1",
      exportTime: [
          this.formatDate(monday),
          this.formatDate(sunday),
      ],
      deriveVisible: false,
      haveDinner:false,
      radioType: 1,
      radioTypefudo: 0,
      comboId: "",
      zhand: [],
      dinnerList: [
        [
          [
            {
              comboId: "",
              num: ""
            }
          ],
          [
            {
              foodId: "",
              num: ""
            }
          ]
        ],
        [
          [
            {
              comboId: "",
              num: ""
            }
          ],
          [
            {
              foodId: "",
              num: ""
            }
          ]
        ],
        [
          [
            {
              comboId: "",
              num: ""
            }
          ],
          [
            {
              foodId: "",
              num: ""
            }
          ]
        ]
      ],
      breakfastList: [
        [
          {
            comboId: "",
            num: ""
          }
        ],
        [
          {
            foodId: "",
            num: ""
          }
        ]
      ],
      pickupList: [
        {
          label: "堂食",
          value: 0
        },
        {
          label: "外送",
          value: 1
        }
      ],
      ingredientList: [],
      cuisineId: "",
      searchForm: {
        foodCode: '',
        foodName: '',
        ingredients: '',
        price: '',
        originalPrice: '',
        createBy: '',
        createTime: ''
      },
      bowType:1,
      statusList: [
        {
          value: 0,
          label: "正常"
        },
        {
          value: 1,
          label: "停用"
        },
        {
          value: 2,
          label: "淘汰"
        }
      ],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/food/dish/importData"
      },
      url: process.env.VUE_APP_BASE_API + "/food/upload",
      radio: 1,
      loading: false,
      tableData: [],
      openingHoursList: [
        { value: 1, label: "周一" },
        { value: 2, label: "周二" },
        { value: 3, label: "周三" },
        { value: 4, label: "周四" },
        { value: 5, label: "周五" },
        { value: 6, label: "周六" },
        { value: 7, label: "周日" }
      ],
      multipleSelection: [],
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增菜品',
      submitting: false,
      fileList: [],
      cuisineList: [],
      form: {
        foodName: '',
        image: '',
        openingHours: [],
        ingredients: '',
        allergy: '',
        calories: '',
        comboList: [
          {
            ingredientsName: "",
            ingredientsId: "",
            ingredientsCode: "",
            comboId: ""
          }
        ],
        price: null,
        originalPrice: null,
        sales: null,
        portion: '',
        taste: '',
        description: '',
        status: '0',
        createBy: '',
        createTime: '',
        remark: '',
      },
      rules: {
        foodCode: [
          { required: true, message: '请输入菜品编号', trigger: 'blur' }
        ],
        foodName: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' }
        ],
        taste: [
          { required: true, message: '请输入口味', trigger: 'blur' }
        ],
        portion: [
          { required: true, message: '请输入规格', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入用量', trigger: 'blur' }
        ],
        // allergy: [
        //   { required: true, message: '请输入过敏源', trigger: 'blur' }
        // ],
        image: [
          { required: true, message: '请上传图片', trigger: 'changes' }
        ],

        'comboList': [
          {
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error('至少需要添加一个套餐'));
              } else {
                // 检查每个食材是否填写完整
                const isValid = value.every(item => {
                  return item.comboId;
                });
                if (!isValid) {
                  callback(new Error('请填写完整'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur'
          }
        ]
        // num heat
      },
    }
  },
  created() {
    this.fetchData()
    this.infredient()
    this.zhandian()
    this.caip()
  },
  methods: {
  	getDayOfWeek(dateStr) {
			  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
			  const date = new Date(dateStr);
			  const dayIndex = date.getDay(); // 0 是星期日，1 是星期一，...，6 是星期六
			  return days[dayIndex];
			},
    handerchange(val) {
      if (val == 1) {
        this.form.siteId = null;
        this.form.siteName = null
      }
    },
    getCurrentWeekRange() {
      const now = new Date();
  const day = now.getDay(); // 0（周日）到6（周六）
  
  // 计算下周一（本周一 +7天）
  const nextMonday = new Date(now);
  nextMonday.setDate(now.getDate() + (day === 0 ? 1 : 8 - day));
  
  // 计算下周日（下周一 +6天）
  const nextSunday = new Date(nextMonday);
  nextSunday.setDate(nextMonday.getDate() + 6);
  
  return [nextMonday, nextSunday];
    },
     formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    async exportConfirmed() {
  // 检查是否选择了时间范围
  if (!this.exportTime || this.exportTime.length !== 2) {
    this.$message.warning('请选择完整的导出时间范围');
    return;
  }

  // 计算日期差
  const startDate = new Date(this.exportTime[0]);
  const endDate = new Date(this.exportTime[1]);
  const diffTime = Math.abs(endDate - startDate);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1; // 包含开始和结束日期的天数

  // 检查是否超过7天
  if (diffDays > 7) {
    this.$message.warning('导出时间范围不能超过7天');
    return;
  }

  // 执行导出
  // this.downloads(`food/export/excel?startDate=${this.exportTime[0]}&endDate=${this.exportTime[1]}&type=${this.deriveRadio}&eatType=${this.eatType}`, {
  //   startDate: this.exportTime[0],
  //   endDate: this.exportTime[1],
  //   type: this.deriveRadio,
  //   eatType: this.eatType
  //     }, `订单导出${new Date().toISOString().slice(0, 10)}.xlsx`);
      // nameding.nameding(`food/export/excel?startDate=${this.exportTime[0]}&endDate=${this.exportTime[1]}&type=${this.deriveRadio}&eatType=${this.eatType}`)

      const res = await fooexcelrs(
        {
          startDate: this.exportTime[0],
          endDate: this.exportTime[1],
          type: this.deriveRadio,
          eatType: this.eatType,
          bowType:this.bowType
        }
      )
      nameding.name(res.msg)
      // const url = "https://www.bhzgst.com.cn/prod/common/download/" + res.msg
      //   const a = document.createElement('a');
      //   a.href = url;
      // a.download = '导出文件.xls'; // 设置文件名
      // a.target = '_blank'; // 新标签页打开
      //   document.body.appendChild(a);
      //   a.click();
      //   window.URL.revokeObjectURL(url);
      //   document.body.removeChild(a);
},
    isIngredientDisabled(ingredientsId, currentIndex) {
    return this.breakfastList[0].some((item, index) => 
      index !== currentIndex && item.comboId === ingredientsId
    );
    },
    isIngredientDisableds(ingredientsId, currentIndex) {
    return this.breakfastList[1].some((item, index) => 
      index !== currentIndex && item.foodId === ingredientsId
    );
    },
  // breakfastList[1]
    qiehuan(val) {
      console.log(val)
      console.log(this.radioTypefudo)
      if (this.radioTypefudo == 0) {
        this.dinnerList[0] = this.breakfastList
        // this.breakfastList = this.dinnerList[val]
      } else if (this.radioTypefudo == 1) {
        this.dinnerList[1] = this.breakfastList
        // this.breakfastList = this.dinnerList[val]
      } else {
        // this.dinnerList[2] = this.breakfastList[val]
      }

      // breakfastList
      this.$nextTick(() => {
        this.breakfastList = JSON.parse(JSON.stringify(this.dinnerList[val]))
      })
      this.radioTypefudo = val;
    },
    addCombo() {
      this.breakfastList[0].push({
        comboId: "",
        num: ""
      })
    },
    addFood() {
      this.breakfastList[1].push({
        foodId: "",
        num: ""
      })
    },
    // cuisineList
    async caip() {
      const res = await GETcuisineList({
        pageNum: 1,
        pageSize: 99999999
      })
      this.cuisineList = res.rows
    },
    deleteCuisine(val) {
      this.cuisineList.forEach(el => {
        if (el.foodId == val.foodId) {
          el.disabled = false;
        }
      });
      this.$forceUpdate()
    },
    async onChangeCuisine(val) {
      this.cuisineList.forEach(el => {
        if (el.foodId == val) {
          el.disabled = true;
        }
      });
    },
    // onChangeCuisine
    deleteDishComb(val) {
      this.ingredientList.forEach(el => {
        if (el.comboId == val.comboId) {
          el.disabled = false;
        }
      });
      this.$forceUpdate()
      console.log(this.ingredientList)
    },
    onChange(val) {
      console.log(val)
      this.ingredientList.forEach(el => {
        if (el.comboId == val) {
          el.disabled = true;
        }
      });
    },
    async zhandian() {
      const res = await listDept({
        pageNum: 1,
        pageSize: 99999999
      })
      this.zhand = res.rows
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.deriveVisible = true;
    },
    handleImport() {
      this.upload.title = "菜品导入"
      this.upload.open = true
    },
    importTemplate() {
      const link = document.createElement('a');
      link.href = '/菜品导入模板.xlsx'; // 路径相对于 public
      link.download = '菜品导入模板.xlsx'; // 下载后的文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    deleteFoodItems(item, index, i) {
      if (i == 1) {
        this.breakfastList[0].splice(index, 1);
      } else {
        this.breakfastList[1].splice(index, 1);
      }
      // this.form.comboList.splice(index, 1); // 从 index 位置删除 1 个元素
    },
    beforeUpload(file) {
      const isImage = file.type.includes('image/');
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error('只能上传图片文件！');
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB！');
      }

      return isImage && isLt5M;
    },
    async infredient() {
      const data = await getlists({ pageNum: 1, pageSize: 99999999,status:0 })
      this.ingredientList = data.rows
    },

    getStatusType(status) {
      const statusMap = {
        '0': 'warning',  // 停用
        '1': 'success',  // 停用
        '2': 'info', // 正常
        '3': 'danger', // 淘汰
        '4': 'info',     // 其他状态
        '5': 'danger',     // 其他状态

      }
      return statusMap[status] || ''
    },
    getStatusText(status) {
      const statusTextMap = {
        '0': '待支付',
        '1': '已下单',
        '2': '审核中',
        '3': '已取消',
        '4': '已取餐',
        '5': '未取餐',
      }
      return statusTextMap[status] || '未知'
    },
    inputGroup() {
      if (this.radio == 2) {
        this.searchForm.status = '1'
      } else if (this.radio == 3) {
        this.searchForm.status = '5'
      } else {
        this.searchForm.status = ''
      }
      this.fetchData()
    },
    // 获取菜品列表
    async fetchData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        const data = await getList(params)
        this.tableData = data.rows
        this.pagination.total = data.total
      } catch (error) {
        console.error(error)
        this.$message.error('获取菜品列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1
      this.fetchData()
    },

    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.radio = 1
      this.searchForm.status = ''
      this.handleSearch()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.fetchData()
    },

    // 表格选择变化
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 新增菜品
    handleAdd() {
      this.dialogTitle = '新增菜品'
      this.resetForm()
      this.dialogVisible = true
    },

    // 编辑菜品
    async handleEdit(rows) {
      const U = this.dict.type.food_eat_type
      this.haveDinner = false
      this.dialogTitle = '编辑菜品'
   
      const res = await fooorderulars(rows.orderId)
      const row = res.data
      this.dinnerList = [
        [
          [
            {
              comboId: "",
              num: ""
            }
          ],
          [
            {
              foodId: "",
              num: ""
            }
          ]
        ],
        [
          [
            {
              comboId: "",
              num: ""
            }
          ],
          [
            {
              foodId: "",
              num: ""
            }
          ]
        ],
        [
          [
            {
              comboId: "",
              num: ""
            }
          ],
          [
            {
              foodId: "",
              num: ""
            }
          ]
        ]
      ],
      row.dishList.forEach(el => {
        if (!this.dinnerList[el.type - 1][1][0].num) {
          this.dinnerList[el.type - 1][1] = []
        }
         this.dinnerList[el.type - 1][1].push({foodId:el.foodId,num:el.saleNum})
      })

      row.comboList.forEach(el => {
        // if (this.dinnerList[el.type - 1][0][0].num) {
        // }
        if (!this.dinnerList[el.type - 1][0][0].num) {
          this.dinnerList[el.type - 1][0] = []
        }
         this.dinnerList[el.type - 1][0].push({num:el.saleNum,comboId:el.comboId})
      })
      this.$forceUpdate()

      this.form = JSON.parse(JSON.stringify(row));


      console.log(U)
      const T = U.length > 0 ? U[0].value - 1 : 0
      console.log(T)

      this.radioType = T
      this.radioTypefudo = T;
      
      
      console.log(this.dinnerList)
      this.$nextTick(() => {
        this.breakfastList = JSON.parse(JSON.stringify(this.dinnerList[T]))
        this.haveDinner = true;

      console.log(this.breakfastList)
      
    })
     
      // this.ingredientList.forEach(el => {
      //   el.disabled = false;
      // })
      // this.cuisineList.forEach(el => {
      //   el.disabled = false;
      // })
      // this.ingredientList.forEach(el => {
      //   this.form.comboList.forEach(els => {
      //     if (el.comboId == els.comboId) {
      //       el.disabled = true;
      //     }
      //   })
      // })

      // this.cuisineList.forEach(el => {
      //   this.form.dishList.forEach(els => {
      //     if (el.foodId == els.foodId) {
      //       el.disabled = true;
      //     }
      //   })
      // })
      // console.log(this.form)
      this.dialogVisible = true
    },

    // 批量编辑
    handleBatchEdit() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }
      if (this.multipleSelection.length > 1) {
        this.$message.warning('暂不支持批量编辑')
        return
      }
      this.handleEdit(this.multipleSelection[0])
    },

    // 删除订单为
    handleDelete(row) {
      this.$confirm(`确定删除订单为【${row.orderCode}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteInent(row.orderId)
          this.$message.success('删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => { })
    },

    // picked
    picked(row,id) {
      this.$confirm(`确定未取餐订单为【${row.orderCode}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await sttofnoTakeMeal({orderId:row.orderId,operate:id})
          this.$message.success('操作成功')
          this.fetchData()
        } catch (error) {
          console.log(error)
          this.$message.error('操作失败')
        }
      }).catch(() => { })
    },

    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }
      const names = this.multipleSelection.map(item => item.orderCode).join('、')
      this.$confirm(`确定删除选中的${this.multipleSelection.length}条记录吗?【${names}】`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.multipleSelection.map(item => item.orderId).join(',')
          await deleteInent(ids)
          this.$message.success('批量删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => { })
    },
    addIngredients() {
      this.form.comboList.push(
        {
          ingredientsName: "",
          ingredientsId: "",
          ingredientsCode: "",
          comboId: "",
          num: null // 确保有 num 字段
        }
      )
    },
    // 重置表单
    resetForm() {
      this.form = {
        foodName: '',
        image: '',
        ingredients: '',
        allergy: '',
        calories: '',
        price: null,
        originalPrice: null,
        sales: null,
        portion: '',
        comboList: [
          {
            ingredientsName: "",
            ingredientsId: "",
            ingredientsCode: "",
            comboId: ""
          }
        ],
        taste: '',
        description: '',
        status: '0',
        createBy: this.$store.state.user.name,
        remark: '',
        params: {}
      }
      this.fileList = []
      this.$nextTick(() => {
        this.$refs.foodForm && this.$refs.foodForm.clearValidate()
      })
    },
    generateNumericId() {
      // 时间戳（13位）
      const timestamp = Date.now();
      // 随机数（5位）
      const randomNum = Math.floor(Math.random() * 90000000000000) + 10000000000000; // 10000 ~ 99999
      return `${timestamp}${randomNum}`; // 如 "16789012345678942001"
    },
    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.foodForm.validate()
        this.submitting = true
        // 设置创建人
        // this.form.createBy = this.$store.state.user.name
        // 更新菜品
        // this.radioType
        this.dinnerList[this.radioType] = this.breakfastList
        // this.breakfastList = this.dinnerList[val]
        console.log(this.form)
        this.$message.success('菜品更新成功')
        console.log(this.dinnerList)
        const T = [];
        const S = [];
        this.dinnerList.forEach(el => {
          el[0].forEach(els => {
              if (els.comboId) {
                // T.push(els)
                if (this.ingredientList.filter(el => el.comboId == els.comboId).length > 0) {
                  if (els.num > 0) {
                  T.push({...this.ingredientList.filter(el => el.comboId == els.comboId)[0],saleNum:els.num})
                    
                  }
                }
              }
          })
          el[1].forEach(els => {
              if (els.foodId) {
                // T.push(els)
                if (this.cuisineList.filter(el => el.foodId == els.foodId).length > 0) {
                  if (els.num > 0) {
                   S.push({...this.cuisineList.filter(el => el.foodId == els.foodId)[0],saleNum:els.num})
                  }
                }
              }
           })
        })
        if (T.length < 1 && S < 1) {
          this.$message.warning("请选择套餐或菜品")
          return false
        }
        // zhand
        if (this.form.type == 1) {
          this.form.siteName = this.zhand.filter(el=>el.id == this.form.siteId)[0].siteName
        }

        console.log(T)
        
        console.log(S)
     
        this.form.dishList = S;
        this.form.comboList = T;
        if (this.form.uuid) {
          return false;
        }
        this.form.uuid = this.generateNumericId()
        await ComboUpdate(this.form)
        this.dialogVisible = false
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error(error)
          this.$message.warning(error)
        }
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style scoped>

::v-deep .el-dialog__headerbtn .el-dialog__close {
  font-size: 25px;
}

::v-deep .el-dialog {
  border-radius: 15px;
}

::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}

.approval-container {
  padding: 20px;
  background: #fff;
}

.search-wrapper {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-direction: column;
}

.search-row {
  display: flex;
  margin-bottom: 15px;
}

.search-row .el-form-item {
  margin-right: 20px;
  margin-bottom: 0;
}

.search-actions {
  margin-left: auto;
  /* padding-right: 10px; */
}

.status-filter {
  margin-bottom: 15px;
}

.table-wrapper {
  margin-top: 20px;
}

.content-cell {
  padding: 5px 0;
}

.content-cell p {
  margin: 5px 0;
  line-height: 1.5;
}

::v-deep .el-dialog__body {
  padding-top: 8px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-table::before {
  display: none;
}

.el-table {
  border: none;
}

.el-table /deep/ th {
  border-bottom: 1px solid #ebeef5;
}

.el-table /deep/ td {
  border-bottom: 1px solid #ebeef5;
}

.el-input-number {
  width: 100%;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  background-color: #4C6EE2;
  border: 1px solid #4C6EE2;
  color: black;
}

::v-deep .el-radio__input.is-checked+.el-radio__label {
  color: black;
}

::v-deep .el-form-item {
  margin-bottom: 8px;
  margin-right: 0;
}

::v-deep .el-input--medium .el-input__inner {
  height: 32px;
  line-height: 32px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0);
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.2);
}

::v-deep .dialogN .el-input--medium .el-input__inner {
  height: 42px;
  line-height: 42px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0);
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.2);
}
</style>